import { getScreenHouseData, getScreenSchoolData } from "@/api/dataAsset";
import { HouseParams, HouseResData, SchoolResData } from "@/api/types/dataAsset";
import { EChartsOption } from "echarts";
import { useEffect, useState } from "react";
import { createSchoolEchartsOption } from "../config/echarts";

// 获取房屋数据
export function useHouseData() {
  const [houseData, setHouseData] = useState<HouseResData>([]),
    [houseTotal, setHouseTotal] = useState<number>(0)

  const request = async (type: HouseParams['type'] = 'price') => {
    try {
      const res = await getScreenHouseData({ type })

      if (res.code === 200) {
        setHouseData(res.data)
        setHouseTotal(res.data.reduce((prev, item) => prev + item.count, 0))
      }

    } catch (error) {
      console.error(error)
    }
  }

  useEffect(() => {
    request()
  }, [])

  return [houseData, houseTotal, request] as const
}

// 获取学校数据
export function useScreenSchool() {
  const [schoolData, setSchoolData] = useState<SchoolResData>([]),
    [echartsOption, setEchartOption] = useState<EChartsOption>({}),
    [mapId] = useState<string>('anhui')

  const getSchoolData = async () => {
    try {
      const res = await getScreenSchoolData()

      if (res.code === 200) {
        setSchoolData(res.data)
        setEchartOption(createSchoolEchartsOption(res.data, mapId))
      }
    } catch (error) {
      console.error(error)
    }
  }

  useEffect(() => {
    getSchoolData()
  }, [])

  return [
    mapId,
    echartsOption
  ] as const
}